<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use App\Http\Resources\Admin\Shop as ShopResources;
use App\Http\Resources\Admin\ShopCollection;
use App\Models\Shop;
use Validator;

class ShopController extends ApiController
{
    /**
     * 店铺列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $limit = $request->input('size', 15);
        $shopOrm = Shop::orderBy('created_at','DESC');

        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $pattern = '/^1([0-9]{9})/'; 
            if (preg_match($pattern, $keyword)) {
                // 是手机号
                $shopOrm->where('tel', $keyword);
            }else{
                // 不是手机号根据店面查找
                $shopOrm->where('name', 'like', '%'.$keyword.'%');
            }
        }

        if ($request->filled('type')) {
            $shopOrm->where('type', $request->input('type'));
        }

        // 根据店铺审核状态查找
        if($request->filled('check') && in_array($request->input('check'), [-1, 0, 1])) {
            $shopOrm->where('check', $request->input('check'));
        }

        return new ShopCollection($shopOrm->paginate($limit));
    }


    /**
     * 创建一个新的店铺
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $messages = [
            'name.required' => '请填写店铺名称',
            'telephone.required' => '请填写手机号码',
            'address.required' => '请填写地区',
            'profile.required' => '请填写店铺介绍'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'telephone' => 'required',
            'address' => 'required',
            'profile' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $store = new Shop();
        $store->user_id = 0;
        $store->name = $request->input('name');
        $store->tel = $request->input('telephone');
        $store->profile = $request->input('profile');
        $store->address = $request->input('address');
        $store->check = 1;
        $store->type = 1; // 自营店
        $store->save();

        if(!$store){
            return $this->failed('店铺创建失败');
        }else {
            return $this->message('店铺创建成功');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * 启用、禁用
     *
     * @return void
     */
    public function toggleStatus(Request $request)
    {
        $status = $request->input('status');
        $ids = $request->input('ids');

        if(!is_array($ids) || count($ids) < 1) {
            return $this->failed('请选择店铺');
        }

        $shopOrm = Shop::whereIn('id', $ids);
        if ($shopOrm->count() !== count($ids)) {
            return $this->failed('修改失败，数据出错');
        }

        if (in_array($status, [0, 1])) {
            $shopOrm->update(['status' => $status]);
        }

        return $this->message('操作成功');
    }

    /**
     * 登录店铺 零时方案
     *
     * @return void
     */
    public function loginToManager($id)
    {
        $shop = Shop::where('type', 1)->where('id', $id)->first();
        \Laravel\Passport\Passport::personalAccessClient(2);
        $token = $shop->createToken($shop->id, ['shop'])->accessToken;

        return $this->success(compact('token'));
    }

    /**
     * 店铺审核
     */
    public function storecheck(Request $request)
    {
        $check = $request->input('check');
        $id = $request->input('id');
        // 做一些验证
        $mystore = Store::find($id);

        if(!$mystore) {
            return $this->failed(['data' => '没有此店铺', 'result' => 'fail']);
        }

        // 传递的check 为 1 审核通过
        if ($check === 2) {
            //if(!in_array($mystore->check, [-1 ,1])) {
            if($mystore->check != 1) {
                return $this->failed(['data' => '此状态不允许审核通过', 'result' => 'fail']);
            }

            $mystore->check = 2;
            if ($mystore->save()) {
                return $this->success(['data' => '该店铺通过了审核', 'result' => 'success']);
            } else {
                return $this->failed(['data' => '数据保存失败，请重试', 'result' => 'fail']);
            }
        }

        if ($check === -1 ) {
            // TODO
            if($mystore->check != 1) {
                return $this->failed(['data' => '此状态不允许审核通过', 'result' => 'fail']);
            }

            $mystore->check = -1;
            if ($mystore->save()) {
                return $this->success(['data' => '该店铺未能通过审核', 'result' => 'fail']);
            } else {
                return $this->failed(['data' => '数据保存失败，请重试', 'result' => 'fail']);
            }
        }

        return $this->failed(['data' => '出错', 'result' => 'fail']);
    }

    /**
     * 查询店铺审核信息
     */
    public function checklist(Request $request)
    {
        $limit = $request->input('size', 15);
        $mystore = Store::select()->with(['user'])->where('check', 1);  //选择未认证的个人信息
        return $this->success($mystore->paginate($limit));
        //return $this->success(User::paginate($limit)->where('check', 0));
    }

}
